// 主应用逻辑
class App {
    constructor() {
        this.currentPage = 1;
        this.currentTab = 'home';
        this.loading = false;
        this.init();
    }

    async init() {
        // 初始化组件
        Components.initModals();
        
        // 绑定事件
        this.bindEvents();
        
        // 加载初始数据
        await this.loadInitialData();
        
        // 初始化工具
        Utils.scrollReveal();
        Utils.lazyLoad();
    }

    bindEvents() {
        // 标签切换
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const tab = item.dataset.tab;
                this.switchTab(tab);
            });
        });

        // 发布动态
        document.getElementById('publishBtn').addEventListener('click', () => {
            this.publishPost();
        });

        // 加载更多
        document.getElementById('loadMorePosts').addEventListener('click', () => {
            this.loadMorePosts();
        });

        // 工具按钮
        document.getElementById('addImageBtn').addEventListener('click', () => {
            this.selectImages();
        });

        document.getElementById('addVideoBtn').addEventListener('click', () => {
            this.selectVideo();
        });

        document.getElementById('addMoodBtn').addEventListener('click', () => {
            this.selectMood();
        });

        document.getElementById('addLocationBtn').addEventListener('click', () => {
            this.selectLocation();
        });

        // 编辑资料
        document.getElementById('editProfileBtn').addEventListener('click', () => {
            this.editProfile();
        });

        // 分享空间
        document.getElementById('shareBtn').addEventListener('click', () => {
            this.shareSpace();
        });

        // 主题切换
        document.getElementById('themeToggle').addEventListener('click', () => {
            this.toggleTheme();
        });

        // 通知按钮
        document.getElementById('notificationBtn').addEventListener('click', () => {
            this.showNotifications();
        });

        // 滚动事件
        window.addEventListener('scroll', Utils.throttle(() => {
            this.handleScroll();
        }, 100));
    }

    async loadInitialData() {
        // 加载动态
        await this.loadPosts();
        
        // 加载访客
        await this.loadVisitors();
        
        // 加载相册
        await this.loadAlbums();
        
        // 加载视频
        await this.loadVideos();
        
        // 加载日志
        await this.loadBlogs();
    }

    async loadPosts() {
        try {
            this.setLoading(true);
            const response = await API.getPosts(this.currentPage);
            const postsContainer = document.getElementById('postsContainer');
            
            if (this.currentPage === 1) {
                postsContainer.innerHTML = response.data.map(post => 
                    Components.renderPost(post)
                ).join('');
            } else {
                response.data.forEach(post => {
                    postsContainer.insertAdjacentHTML('beforeend', 
                        Components.renderPost(post)
                    );
                });
            }
            
            // 重新初始化滚动显示
            Utils.scrollReveal();
        } catch (error) {
            Utils.showToast('加载动态失败');
        } finally {
            this.setLoading(false);
        }
    }

    async loadMorePosts() {
        if (this.loading) return;
        
        this.currentPage++;
        await this.loadPosts();
    }

    async loadVisitors() {
        try {
            const visitors = await API.getVisitors();
            const visitorsList = document.getElementById('visitorsList');
            visitorsList.innerHTML = visitors.map(visitor => 
                Components.renderVisitor(visitor)
            ).join('');
        } catch (error) {
            console.error('加载访客失败:', error);
        }
    }

    async loadAlbums() {
        try {
            const albums = await API.getAlbums();
            const albumGrid = document.getElementById('albumGrid');
            albumGrid.innerHTML = albums.map(album => 
                Components.renderAlbum(album)
            ).join('');
        } catch (error) {
            console.error('加载相册失败:', error);
        }
    }

    async loadVideos() {
        try {
            const videos = await API.getVideos();
            const videoGrid = document.getElementById('videoGrid');
            videoGrid.innerHTML = videos.map(video => 
                Components.renderVideo(video)
            ).join('');
        } catch (error) {
            console.error('加载视频失败:', error);
        }
    }

    async loadBlogs() {
        try {
            const blogs = await API.getBlogs();
            const blogList = document.getElementById('blogList');
            blogList.innerHTML = blogs.map(blog => 
                Components.renderBlog(blog)
            ).join('');
        } catch (error) {
            console.error('加载日志失败:', error);
        }
    }

    async publishPost() {
        const content = document.getElementById('postContent').value.trim();
        
        if (!content) {
            Utils.showToast('请输入内容');
            return;
        }
        
        try {
            this.setLoading(true);
            await API.createPost(content);
            
            // 清空输入框
            document.getElementById('postContent').value = '';
            
            // 重新加载动态
            this.currentPage = 1;
            await this.loadPosts();
            
            Utils.showToast('发布成功！');
        } catch (error) {
            Utils.showToast('发布失败，请重试');
        } finally {
            this.setLoading(false);
        }
    }

    switchTab(tabName) {
        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        // 切换内容
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.remove('active');
        });
        document.getElementById(tabName).classList.add('active');
        
        this.currentTab = tabName;
        
        // 重新初始化滚动显示
        setTimeout(() => {
            Utils.scrollReveal();
        }, 100);
    }

    selectImages() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.multiple = true;
        input.onchange = (e) => {
            const files = Array.from(e.target.files);
            Utils.showToast(`已选择 ${files.length} 张图片`);
        };
        input.click();
    }

    selectVideo() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'video/*';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                Utils.showToast(`已选择视频: ${file.name}`);
            }
        };
        input.click();
    }

    selectMood() {
        const moods = ['😊', '😎', '😴', '🤔', '😭', '🥳', '😡', '🤗'];
        const mood = moods[Math.floor(Math.random() * moods.length)];
        Utils.showToast(`当前心情: ${mood}`);
    }

    selectLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    Utils.showToast('位置获取成功');
                },
                (error) => {
                    Utils.showToast('位置获取失败');
                }
            );
        } else {
            Utils.showToast('浏览器不支持定位');
        }
    }

    editProfile() {
        Utils.showToast('编辑资料功能开发中...');
    }

    shareSpace() {
        if (navigator.share) {
            navigator.share({
                title: '我的QQ空间',
                text: '快来看看我的QQ空间！',
                url: window.location.href
            });
        } else {
            navigator.clipboard.writeText(window.location.href);
            Utils.showToast('链接已复制到剪贴板');
        }
    }

    toggleTheme() {
        document.body.classList.toggle('dark-theme');
        const isDark = document.body.classList.contains('dark-theme');
        const icon = document.querySelector('#themeToggle i');
        icon.className = isDark ? 'fas fa-sun' : 'fas fa-moon';
        Utils.showToast(isDark ? '已切换到深色模式' : '已切换到浅色模式');
    }

    showNotifications() {
        Utils.showToast('暂无新通知');
    }

    handleScroll() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const header = document.querySelector('.header');
        
        // 头部阴影效果
        if (scrollTop > 10) {
            header.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
        } else {
            header.style.boxShadow = 'var(--shadow)';
        }
    }

    setLoading(loading) {
        this.loading = loading;
        const loadMoreBtn = document.getElementById('loadMorePosts');
        if (loadMoreBtn) {
            const icon = loadMoreBtn.querySelector('i');
            if (loading) {
                icon.className = 'fas fa-spinner loading';
                loadMoreBtn.disabled = true;
            } else {
                icon.className = 'fas fa-spinner';
                loadMoreBtn.disabled = false;
            }
        }
    }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
    new App();
});
